package lbframework.bean.internalFrame;

import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JInternalFrame;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.event.InternalFrameEvent;
import lbframework.bean.button.LBButton;
import lbframework.bean.calendar.LBCalendar;
import lbframework.bean.checkBox.LBCheckBox;
import lbframework.bean.comboBox.LBComboBox;
import lbframework.bean.consultaCampo.LBConsultaCampo;
import lbframework.bean.fileChooser.LBFileChooser;
import lbframework.bean.mdiFrame.LBMdiFrame;
import lbframework.bean.passwordField.LBPasswordField;
import lbframework.bean.radioButton.LBRadioButton;
import lbframework.bean.table.LBTable;
import lbframework.bean.textArea.LBTextArea;
import lbframework.bean.textAreaEx.LBTextAreaEx;
import lbframework.bean.textField.LBTextField;
import lbframework.bean.time.LBTime;
import lbframework.bean.toolBar.LBToolBar;
import lbframework.bean.toolBarPadrao.LBToolBarPadrao;
import lbframework.bean.tree.LBItemNode;
import lbframework.bean.tree.LBTree;
import lbframework.classe.OperacaoCanceladaException;
import lbframework.classe.Util;
import lbframework.remote.Arquivo;

public class LBInternalFrame extends JInternalFrame {

    protected LBMdiFrame mdiFrame = null;
    protected LBConsultaCampo consultaCampo = null;
    private Vector<Component> vComponent = null;
    private StringBuilder estadoTela;
    private String estadoInicial = "";
    private String estadoFinal = "";
    private boolean enabledSalvar = false;

    public LBInternalFrame(LBMdiFrame i_mdiFrame) throws Exception {
        initComponents();

        mdiFrame = i_mdiFrame;
        mdiFrame.desktopPane.add(this);

        setEscape();
    }

    public void consultar() throws Exception {
    }

    public void finalizar() throws Exception {
    }

    public void filtro() throws Exception {
    }

    public void importar() throws Exception {
    }

    public void editar() throws Exception {
    }

    public void incluir() throws Exception {
    }

    public void salvar() throws Exception {
    }

    public void excluir() throws Exception {
    }

    public void imprimir() throws Exception {
    }

    public void sair() throws Exception {
        this.dispose();
    }

    @Override
    public void dispose() {
        if (isVisible()) {
            setVisible(false);
        }
//        if (isSelected()) {
//            try {
//                setSelected(false);
//            } catch (PropertyVetoException pve) {}
//        }
        if (!isClosed) {
            firePropertyChange(IS_CLOSED_PROPERTY, Boolean.FALSE, Boolean.TRUE);
            isClosed = true;
        }
        fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_CLOSED);
    }

    public void cancelar() throws Exception {
    }

    public void iniciar() throws Exception {
    }

    public void copiar() throws Exception {
    }

    public void baixar() throws Exception {
    }

    public void exportar() throws Exception {
    }

    public void parametrizar() throws Exception {
    }

    public void configurar() throws Exception {
    }

    public void estornar() throws Exception {
    }

    public void centralizarForm() throws Exception {
        Dimension ds = mdiFrame.desktopPane.getSize();
        Dimension dw = this.getSize();

        int x = (ds.width - dw.width) / 2;
        int y = (ds.height - dw.height) / 3;

        if (x < 0) {
            x = 0;
        }

        if (y < 0) {
            y = 0;
        }

        setLocation(x, y);
    }

    private void carregarPosicaoForm() throws Exception {
        Arquivo arqGUI = null;

        try {
            arqGUI = new Arquivo(Util.getRoot() + Util.FILE_LOG_GUI, "r");

            while (arqGUI.ready()) {
                String line = arqGUI.readLine();

                if (line.startsWith(getClass().getName())) {
                    String[] vPosicao = line.split(";");

                    int maximum = Integer.parseInt(vPosicao[1]);
                    int top = Integer.parseInt(vPosicao[2]);
                    int left = Integer.parseInt(vPosicao[3]);
                    int width = Integer.parseInt(vPosicao[4]);
                    int height = Integer.parseInt(vPosicao[5]);

                    if (maximum == 1) {
                        this.setMaximum(true);

                    } else {
                        this.setMaximum(false);
                        setSize(new Dimension(width, height));
                        setLocation(new Point(left, top));
                    }

                    break;
                }
            }
        } catch (Exception ex) {
        } finally {
            try {
                arqGUI.close();
            } catch (Exception ex) {
            }
        }
    }

    private void salvarPosicaoForm() throws Exception {
        Vector<String> vLine = new Vector();
        Arquivo arqGUI = null;

        try {
            arqGUI = new Arquivo(Util.getRoot() + Util.FILE_LOG_GUI, "r");

            while (arqGUI.ready()) {
                String line = arqGUI.readLine();

                if (!line.startsWith(getClass().getName())) {
                    vLine.add(line);
                }
            }
        } catch (Exception ex) {
        } finally {
            try {
                arqGUI.close();
            } catch (Exception ex) {
            }
        }

        try {
            arqGUI = new Arquivo(Util.getRoot() + Util.FILE_LOG_GUI, "w");

            String posicao = getClass().getName() + ";";
            posicao += (isMaximum ? "1" : "0") + ";";
            posicao += getLocation().y + ";";
            posicao += getLocation().x + ";";
            posicao += getSize().width + ";";
            posicao += getSize().height;

            vLine.add(posicao);

            for (String line : vLine) {
                arqGUI.write(line);
            }
        } catch (Exception ex) {
        } finally {
            try {
                arqGUI.close();
            } catch (Exception ex) {
            }
        }
    }

    public void setDefaultCursor() {
        this.setCursor(Cursor.getDefaultCursor());
    }

    public void setWaitCursor() {
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    }

    public void verificarAlteracaoTela() throws Exception {
        try {
            if (estadoInicial.isEmpty()) {
                return;
            }

            enabledSalvar = false;
            isEnabledSalvar(this.getComponents());

            if (!enabledSalvar) {
                return;
            }

            getEstadoTelaFinal();

            if (!estadoFinal.equals(estadoInicial)) {
                final JButton btnSim = new JButton("Sim");
                final JButton btnNao = new JButton("Não");
                final JButton btnCancelar = new JButton("Cancelar");
                final Object[] options = {btnSim, btnNao, btnCancelar};
                final JOptionPane option = new JOptionPane("Deseja salvar as alterações?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]);

                btnSim.addKeyListener(new KeyAdapter() {

                    @Override
                    public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                            btnNao.requestFocus();
                        } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                            btnCancelar.requestFocus();
                        }
                    }
                });

                btnNao.addKeyListener(new KeyAdapter() {

                    @Override
                    public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                            btnCancelar.requestFocus();
                        } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                            btnSim.requestFocus();

                        }
                    }
                });

                btnCancelar.addKeyListener(new KeyAdapter() {

                    @Override
                    public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                            btnNao.requestFocus();
                        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                            btnSim.requestFocus();
                        }
                    }
                });

                btnSim.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        option.setValue(JOptionPane.YES_OPTION);
                    }
                });

                btnNao.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        option.setValue(JOptionPane.NO_OPTION);
                    }
                });

                btnCancelar.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        option.setValue(JOptionPane.CANCEL_OPTION);
                    }
                });

                JDialog dialog = option.createDialog(null, this.getTitle());
                option.selectInitialValue();
                dialog.show();
                dialog.dispose();

                Object selectedValue = option.getValue();

                if (((Integer) selectedValue) == null || ((Integer) selectedValue).intValue() == JOptionPane.CANCEL_OPTION) {
                    throw new OperacaoCanceladaException();
                } else if (((Integer) selectedValue).intValue() == JOptionPane.YES_OPTION) {
                    salvar();
                }
            }

        } catch (Exception ex) {
            throw ex;
        }
    }

    private void setEscape() throws Exception {
        this.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ESCAPE"), "sair");
        this.getActionMap().put("sair",
                new AbstractAction("sair") {

                    public void actionPerformed(ActionEvent evt) {
                        try {
                            verificarAlteracaoTela();

                            sair();

                        } catch (Exception ex) {
                            Util.exibirMensagemErro(ex, getTitle());
                        }
                    }
                });
    }

    @Override
    public void setVisible(boolean aFlag) {
        try {
            super.setVisible(aFlag);
            super.setSelected(true);

        } catch (Exception ex) {
        }
    }

    public Vector<Component> getCampoObrigatorio() {
        vComponent = new Vector();

        procurarCampo(this.getComponents());

        return vComponent;
    }

    private void procurarCampo(Component[] i_componente) {
        for (int i = 0; i < i_componente.length; i++) {
            Component oComponente = i_componente[i];

            if (oComponente instanceof LBTextField) {
                LBTextField txtCampo = (LBTextField) oComponente;

                if (txtCampo.isObrigatorio() && txtCampo.isEnabled()) {
                    vComponent.add(oComponente);
                }
            } else if (oComponente instanceof LBTextArea) {
                LBTextArea txtCampo = (LBTextArea) oComponente;

                if (txtCampo.isObrigatorio() && txtCampo.isEnabled()) {
                    vComponent.add(oComponente);
                }
            } else if (oComponente instanceof LBTextAreaEx) {
                LBTextAreaEx txtCampo = (LBTextAreaEx) oComponente;

                if (txtCampo.isObrigatorio() && txtCampo.isEnabled()) {
                    vComponent.add(oComponente);
                }
            } else if (oComponente instanceof LBPasswordField) {
                LBPasswordField txtCampo = (LBPasswordField) oComponente;

                if (txtCampo.isObrigatorio() && txtCampo.isEnabled()) {
                    vComponent.add(oComponente);
                }
            } else if (oComponente instanceof LBComboBox) {
                LBComboBox cboCampo = (LBComboBox) oComponente;

                if (cboCampo.isObrigatorio() && cboCampo.isEnabled()) {
                    vComponent.add(oComponente);
                }
            } else if (oComponente instanceof LBConsultaCampo) {
                LBConsultaCampo cnsCampo = (LBConsultaCampo) oComponente;

                if (cnsCampo.isObrigatorio() && cnsCampo.isEnabled()) {
                    vComponent.add(oComponente);
                }
            } else if (oComponente instanceof LBFileChooser) {
                LBFileChooser flcCampo = (LBFileChooser) oComponente;

                if (flcCampo.isObrigatorio() && flcCampo.isEnabled()) {
                    vComponent.add(oComponente);
                }
            } else if (oComponente instanceof LBCalendar) {
                LBCalendar txtCampo = (LBCalendar) oComponente;

                if (txtCampo.isObrigatorio() && txtCampo.isEnabled()) {
                    vComponent.add(oComponente);
                }
            } else if (oComponente instanceof LBTime) {
                LBTime txtTime = (LBTime) oComponente;

                if (txtTime.isObrigatorio() && txtTime.isEnabled()) {
                    vComponent.add(oComponente);
                }
            } else if (oComponente instanceof JPanel) {
                procurarCampo(((JPanel) oComponente).getComponents());

            } else if (oComponente instanceof JScrollPane) {
                procurarCampo(((JScrollPane) oComponente).getComponents());

            } else if (oComponente instanceof JLayeredPane) {
                procurarCampo(((JLayeredPane) oComponente).getComponents());

            } else if (oComponente instanceof JViewport) {
                procurarCampo(((JViewport) oComponente).getComponents());

            } else if (oComponente instanceof JRootPane) {
                procurarCampo(((JRootPane) oComponente).getComponents());

            } else if (oComponente instanceof JTabbedPane) {
                procurarCampo(((JTabbedPane) oComponente).getComponents());

            } else if (oComponente instanceof JSplitPane) {
                procurarCampo(((JSplitPane) oComponente).getComponents());
            }
        }
    }

    public void getEstadoTelaInicial() throws Exception {
        estadoTela = new StringBuilder();

        obterEstadoTela(this.getComponents());

        estadoInicial = "." + estadoTela.toString();
    }

    private void getEstadoTelaFinal() throws Exception {
        estadoTela = new StringBuilder();

        obterEstadoTela(this.getComponents());

        estadoFinal = "." + estadoTela.toString();
    }

    private void obterEstadoTela(Component[] i_componente) throws Exception {
        for (int i = 0; i < i_componente.length; i++) {
            Component oComponente = i_componente[i];

            if (oComponente instanceof LBTextField) {
                LBTextField txtCampo = (LBTextField) oComponente;

                estadoTela.append(txtCampo.getText());

            } else if (oComponente instanceof LBTextArea) {
                LBTextArea txtCampo = (LBTextArea) oComponente;

                estadoTela.append(txtCampo.getText());

            } else if (oComponente instanceof LBTextAreaEx) {
                LBTextAreaEx txtCampo = (LBTextAreaEx) oComponente;

                estadoTela.append(txtCampo.getText());

            } else if (oComponente instanceof LBPasswordField) {
                LBPasswordField txtCampo = (LBPasswordField) oComponente;

                estadoTela.append(txtCampo.getText());

            } else if (oComponente instanceof LBComboBox) {
                LBComboBox cboCampo = (LBComboBox) oComponente;

                estadoTela.append(cboCampo.getId());

            } else if (oComponente instanceof LBConsultaCampo) {
                LBConsultaCampo cnsCampo = (LBConsultaCampo) oComponente;

                estadoTela.append(cnsCampo.getId());

            } else if (oComponente instanceof LBFileChooser) {
                LBFileChooser flcCampo = (LBFileChooser) oComponente;

                estadoTela.append(flcCampo.getArquivo());

            } else if (oComponente instanceof LBCalendar) {
                LBCalendar txtCampo = (LBCalendar) oComponente;

                estadoTela.append(txtCampo.getClipText());

            } else if (oComponente instanceof LBTime) {
                LBTime txtTime = (LBTime) oComponente;

                estadoTela.append(txtTime.getClipTextHoraInicio() + txtTime.getClipTextHoraTermino());

            } else if (oComponente instanceof LBCheckBox) {
                LBCheckBox chkCampo = (LBCheckBox) oComponente;

                estadoTela.append(chkCampo.isSelected());

            } else if (oComponente instanceof LBRadioButton) {
                LBRadioButton optCampo = (LBRadioButton) oComponente;

                estadoTela.append(optCampo.isSelected());

            } else if (oComponente instanceof LBTable) {
                LBTable tblCampo = (LBTable) oComponente;

                StringBuilder value = new StringBuilder();

                for (int l = 0; l < tblCampo.getRowCount(); l++) {
                    for (int c = 0; c < tblCampo.getColumnCount(); c++) {
                        Object oCelula = tblCampo.getValueAt(l, c);

                        if (oCelula instanceof LBTextField) {
                            LBTextField txtCampo = (LBTextField) oCelula;

                            value.append(txtCampo.getText());

                        } else if (oCelula instanceof LBComboBox) {
                            LBComboBox cboCampo = (LBComboBox) oCelula;

                            value.append(cboCampo.getId());

                        } else if (oCelula instanceof LBCheckBox) {
                            LBCheckBox chkCampo = (LBCheckBox) oCelula;

                            value.append(chkCampo.isSelected());

                        } else if (oCelula instanceof LBRadioButton) {
                            LBRadioButton optCampo = (LBRadioButton) oCelula;

                            value.append(optCampo.isSelected());

                        } else {
                            if (oCelula != null) {
                                value.append(oCelula.toString());
                            }
                        }
                    }
                }

                estadoTela.append(value.toString());

            } else if (oComponente instanceof LBTree) {
                LBTree treCampo = (LBTree) oComponente;

                procurarLBTree(estadoTela, (LBItemNode) treCampo.getModel().getRoot());

            } else if (oComponente instanceof JPanel) {
                obterEstadoTela(((JPanel) oComponente).getComponents());

            } else if (oComponente instanceof JTabbedPane) {
                obterEstadoTela(((JTabbedPane) oComponente).getComponents());

            } else if (oComponente instanceof JScrollPane) {
                obterEstadoTela(((JScrollPane) oComponente).getComponents());

            } else if (oComponente instanceof JLayeredPane) {
                obterEstadoTela(((JLayeredPane) oComponente).getComponents());

            } else if (oComponente instanceof JViewport) {
                obterEstadoTela(((JViewport) oComponente).getComponents());

            } else if (oComponente instanceof JRootPane) {
                obterEstadoTela(((JRootPane) oComponente).getComponents());

            } else if (oComponente instanceof JSplitPane) {
                obterEstadoTela(((JSplitPane) oComponente).getComponents());
            }
        }
    }

    private void isEnabledSalvar(Component[] i_component) throws Exception {
        for (int i = 0; i < i_component.length; i++) {
            Component oComponent = i_component[i];

            if (oComponent instanceof LBToolBarPadrao) {
                LBToolBarPadrao oCampo = (LBToolBarPadrao) oComponent;

                if (oCampo.isEnabledSalvar()) {
                    enabledSalvar = true;
                    return;
                }

            } else if (oComponent instanceof LBButton) {
                LBButton oCampo = (LBButton) oComponent;

                if (oCampo.getIcon().toString().contains("salvar.png")) {
                    if (oCampo.isEnabled()) {
                        enabledSalvar = true;
                        return;
                    }
                }

            } else if (oComponent instanceof LBToolBar) {
                isEnabledSalvar(((LBToolBar) oComponent).getComponents());

            } else if (oComponent instanceof JPanel) {
                isEnabledSalvar(((JPanel) oComponent).getComponents());

            } else if (oComponent instanceof JScrollPane) {
                isEnabledSalvar(((JScrollPane) oComponent).getComponents());

            } else if (oComponent instanceof JLayeredPane) {
                isEnabledSalvar(((JLayeredPane) oComponent).getComponents());

            } else if (oComponent instanceof JViewport) {
                isEnabledSalvar(((JViewport) oComponent).getComponents());

            } else if (oComponent instanceof JRootPane) {
                isEnabledSalvar(((JRootPane) oComponent).getComponents());

            } else if (oComponent instanceof JTabbedPane) {
                isEnabledSalvar(((JTabbedPane) oComponent).getComponents());

            } else if (oComponent instanceof JSplitPane) {
                isEnabledSalvar(((JSplitPane) oComponent).getComponents());
            }
        }
    }

    private void procurarLBTree(StringBuilder i_string, LBItemNode i_lbItemNode) throws Exception {
        estadoTela.append(i_lbItemNode.selecionado);

        for (int l = 0; l < i_lbItemNode.getChildCount(); l++) {
            LBItemNode internalNode = i_lbItemNode.getChild(l);

            procurarLBTree(i_string, internalNode);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameActivated(evt);
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosed(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                formComponentHidden(evt);
            }
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 399, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 292, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameActivated
        try {
            if (!mdiFrame.vJanela.contains(this)) {
                mdiFrame.vJanela.add(this);
            }

            mdiFrame.atualizarJanela();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_formInternalFrameActivated

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        try {
            salvarPosicaoForm();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_formInternalFrameClosing

    private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed
        try {
            mdiFrame.vJanela.remove(this);

            mdiFrame.atualizarJanela();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_formInternalFrameClosed

    private void formComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentHidden
        try {
            mdiFrame.vJanela.remove(this);

            mdiFrame.atualizarJanela();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_formComponentHidden

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
    }//GEN-LAST:event_formComponentShown

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
        try {
            carregarPosicaoForm();

        } catch (Exception ex) {
        }
    }//GEN-LAST:event_formInternalFrameOpened

    public void setConsultaCampo(LBConsultaCampo i_consultaCampo) {
        consultaCampo = i_consultaCampo;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
